package com.example.utils;

import org.apache.commons.collections4.map.LRUMap;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class IdempotentUtil {

    public static LRUMap<String,Integer> lruMap = new LRUMap<>(100);

    public static <T> String calculateHash(T object) {
        try {
            // 创建SHA-256哈希算法的MessageDigest实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将表单数据转换为字符串
            String formDataString;
            if(object instanceof String){
                formDataString = (String)object;
            }else{
                formDataString = object.toString();
            }

            // 将表单数据字符串转换为字节数组
            byte[] formDataBytes = formDataString.getBytes(StandardCharsets.UTF_8);

            // 计算哈希值
            byte[] hashBytes = digest.digest(formDataBytes);

            // 将哈希值转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> boolean judge(String url,T object,Object lockClass){
        synchronized (lockClass){
            String formKey = calculateHash(object);
            String realKey = url+"?"+formKey;
            if(lruMap.containsKey(realKey)){
                lruMap.get(realKey);
                System.out.println("请勿重复提交");
                return false;
            }
            lruMap.put(realKey,1);
        }
        return true;
    }



}